package controller.group_management;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import define.API;
import define.Camera;
import define.Constants;
import define.Extension;
import define.Key;
import ui.activity.group_management.GroupFeed;
import utils.Utils;

/**
 * Created by trek2000 on 9/9/2014.
 */
public class DownloadMultiFilesAsync extends AsyncTask<String, Integer, Boolean> {

    /**
     * Data section
     */

    /**
     * String section
     */
    private boolean IS_CONNECTED_CARD = false;
    private boolean IS_FINISHED_CURRENT_ACTIVITY = false;

    private static int completed_item_index = 0;

    /**
     * View section
     */
    private static ProgressDialog mPd;

    /**
     * The other sections
     */
    private Context mContext;
    // declare the dialog as a member field of your activity

    public DownloadMultiFilesAsync(Context mContext) {
        this.mContext = mContext;
    }

//    public DownloadFileAsync(boolean IS_CONNECTED_CARD, Context mContext) {
//        this.IS_CONNECTED_CARD = IS_CONNECTED_CARD;
//
//        this.mContext = mContext;
//    }
//
//    public DownloadFileAsync(Context mContext, boolean IS_FINISHED_CURRENT_ACTIVITY) {
//        this.mContext = mContext;
//
//        this.IS_FINISHED_CURRENT_ACTIVITY = IS_FINISHED_CURRENT_ACTIVITY;
//
//    }

    @Override
    protected Boolean doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            String URL = null;

            /**
             * Check if connected card or not
             */
            if (API.IS_DEV_SITE) {
                // Case - not connected card
                URL = sUrl[0].replace("https://", "http://");
            } else {
                // Connected card
                URL = sUrl[0];
            }

            URL url = new URL(URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return false;
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();

            // New date - Filename
            // png
            // IMG
            // VIDEO
            Date date = new Date();
            File mFile = new File(Environment.getExternalStorageDirectory() + "/" + Key.ENTERPRISE);

            if (!mFile.exists()) mFile.mkdir();

            String path = mFile.getPath() + "/" + String.valueOf(date.getTime());

            File mFileSpecify = null;
            //check lowercase and uppercase
            if (URL.toLowerCase().contains(Extension.ARW)) {
                mFileSpecify = new File(path + Extension.ARW);
            } else if (URL.toLowerCase().contains(Extension.CR2)) {
                mFileSpecify = new File(path + Extension.CR2);
            } else if (URL.toLowerCase().contains(Extension.CRW)) {
                mFileSpecify = new File(path + Extension.CRW);
            } else if (URL.toLowerCase().contains(Extension.DCR)) {
                mFileSpecify = new File(path + Extension.DCR);
            } else if (URL.toLowerCase().contains(Extension.DNG)) {
                mFileSpecify = new File(path + Extension.DNG);
            } else if (URL.toLowerCase().contains(Extension.JPEG)) {
                mFileSpecify = new File(path + Extension.JPEG);
            } else if (URL.toLowerCase().contains(Extension.JPG)) {
                mFileSpecify = new File(path + Extension.JPG);
            } else if (URL.toLowerCase().contains(Extension.MOV)) {
                mFileSpecify = new File(path + Extension.MOV);
            } else if (URL.toLowerCase().contains(Extension.MP4)) {
                mFileSpecify = new File(path + Extension.MP4);
            } else if (URL.toLowerCase().contains(Extension.MPG)) {
                mFileSpecify = new File(path + Extension.MPG);
            } else if (URL.toLowerCase().contains(Extension.MRW)) {
                mFileSpecify = new File(path + Extension.MRW);
            } else if (URL.toLowerCase().contains(Extension.MTS)) {
                mFileSpecify = new File(path + Extension.MTS);
            } else if (URL.toLowerCase().contains(Extension.NEF)) {
                mFileSpecify = new File(path + Extension.NEF);
            } else if (URL.toLowerCase().contains(Extension.ORF)) {
                mFileSpecify = new File(path + Extension.ORF);
            } else if (URL.toLowerCase().contains(Extension.PEF)) {
                mFileSpecify = new File(path + Extension.PEF);
            } else if (URL.toLowerCase().contains(Extension.PNG)) {
                mFileSpecify = new File(path + Extension.PNG);
            } else if (URL.toLowerCase().contains(Extension.RAF)) {
                mFileSpecify = new File(path + Extension.RAF);
            } else if (URL.toLowerCase().contains(Extension.SR2)) {
                mFileSpecify = new File(path + Extension.SR2);
            } else if (URL.toLowerCase().contains(Extension.WMV)) {
                mFileSpecify = new File(path + Extension.WMV);
            }

            output = new FileOutputStream(mFileSpecify.getPath());

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;

                publishProgress((int) (total * 100 / fileLength));

                output.write(data, 0, count);
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
                ignored.printStackTrace();
            }

            if (connection != null)
                connection.disconnect();
        }
        return false;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // show progress dialog
        mPd = Utils.showProgressDialog(
                mContext,
                mContext.getString(R.string.downloading_),
                (Enterprise.groupManagement.getmAlPhotoAndVDOIsCheckedInGroupFeed().size() -
                        GroupFeed.mAlFilesCheckedToDownload.size()) + " / " +
                        Enterprise.groupManagement.getmAlPhotoAndVDOIsCheckedInGroupFeed().size() + "");
        //Cloudstringers.mHmSelectedItems.size()
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        mPd.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // Hide progress dialog
        Utils.hideProgressDialog();

        if (!result) {
//            // need check show dialog for internet or card
//            if (Cloudstringers.card.getIpAddress().contains(Constants.IP))
//                try {
//                    Utils.showWarningDialog(
//                            false, mContext, mContext.getString(R.string.no_connection_to_card_title),
//                            mContext.getString(R.string.no_connection_to_card_content));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            else
//                try {
//                    Utils.showWarningDialog(
//                            false, mContext, mContext.getString(R.string.no_internet_title),
//                            mContext.getString(R.string.no_internet_content));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            Log.i("","Fail");
            mPd.cancel();
        } else {
            Log.i("", "Success");
            mPd.cancel();
            //remove file download from template array
            GroupFeed.mAlFilesCheckedToDownload.remove(0);
            //continue download if template !empty
            if (GroupFeed.mAlFilesCheckedToDownload.size() > 0) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    new DownloadMultiFilesAsync(mContext).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                            GroupFeed.mAlFilesCheckedToDownload.get(0));
                else
                    new DownloadMultiFilesAsync(mContext).execute(
                            GroupFeed.mAlFilesCheckedToDownload.get(0));
            } else {
                GroupFeed.cancelDownloadFeature();
            }
            /**
             //             * Refresh Gallery to always see new files after downloaded into Gallery
             //             */
//            Utils.refreshGallery(mContext);
//
//            /**
//             * Check connect to card or not
//             */
//            if (!IS_CONNECTED_CARD) {
//                /**
//                 * Case : not connected to card
//                 */
//                if (Cloudstringers.mDialogFileDetail != null) {
//                    if (Cloudstringers.mDialogFileDetail.isShowing()) {
//                        completedDownloadingProgress();
//                    } else {
//                        continueDownloadFile();
//                    }
//                } else {
//                    continueDownloadFile();
//                }
//            } else {
//                /**
//                 * Case : connected to card
//                 */
//                continueDownloadFile();
//            }
        }
    }

//    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
//    private void continueDownloadFile() {
//        if (!Cloudstringers.mAlIndex.isEmpty()) {
//            // Remove item already downloaded
//            Cloudstringers.mAlIndex.remove(0);
//            completed_item_index++;
//
//            mPd.setMessage(completed_item_index + " / "
//                    + Cloudstringers.mHmSelectedItems.size() + "");
//
//            // Continue download new item
//            if (!Cloudstringers.mAlIndex.isEmpty()) {
//                if (!IS_CONNECTED_CARD) {
//                    /**
//                     * Case : not connected to card
//                     */
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
//                        new DownloadFileAsync(mContext).executeOnExecutor(
//                                AsyncTask.THREAD_POOL_EXECUTOR,
//                                Cloudstringers.mHmSelectedItems.get(
//                                        Cloudstringers.mAlIndex.get(0)).getOriginalClip());
//                    else
//                        new DownloadFileAsync(mContext).execute(
//                                Cloudstringers.mHmSelectedItems.get(
//                                        Cloudstringers.mAlIndex.get(0)).getOriginalClip());
//                } else {
//                    /**
//                     * Case : connected to card
//                     */
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
//                        new DownloadFileAsync(true, mContext).executeOnExecutor(
//                                AsyncTask.THREAD_POOL_EXECUTOR, Cloudstringers.mHmSelectedItems.get(
//                                        Cloudstringers.mAlIndex.get(0)).getDownloadURL());
//                    else
//                        new DownloadFileAsync(true, mContext).execute(Cloudstringers.mHmSelectedItems.get(
//                                Cloudstringers.mAlIndex.get(0)).getDownloadURL());
//                }
//            } else {
//                completedDownloadingProgress();
//            }
//        } else {
//            completed_item_index++;
//            completedDownloadingProgress();
//        }
//    }

//    private void completedDownloadingProgress() {
//        // Reset download counter
//        completed_item_index = 0;
//
//        // Hide progress dialog
//        Utils.hideWaitingDialog();
//
//        /**
//         * After download all files, need refresh all views, to begin download again.
//         */
//        if (Cloudstringers.fileItem.getAllItem() == null) {
//            /**
//             * Multiple selection
//             */
//
//            if (!IS_CONNECTED_CARD) {
//                /**
//                 * Case : connected to Internet, not connected to card
//                 */
//                Cloudstringers.onCallbackResetViewsListener
//                        .onResetViews(false, Cloudstringers.mGvFileView, FileViewAsync.mAlCompletedItems);
//            } else {
//                /**
//                 * Case : not connected to Internet, connected to card
//                 */
//                Cloudstringers.onCallbackResetViewsListener
//                        .onResetViews(true, HomeRealCardFragment.mGv, GetPreviewDownloadThumbnailAsync.mAlCompletedItems);
//            }
//        }
//
//        // Finish current activity
//        if (IS_FINISHED_CURRENT_ACTIVITY) {
//            IS_FINISHED_CURRENT_ACTIVITY = false;
//
//            ((Activity) mContext).finish();
//        }
//    }

//    public static void downloadFirstFile(Context mContext, String URL) {
//        try {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
//                new DownloadFileAsync(mContext, false).execute(URL);
//            else
//                new DownloadFileAsync(mContext, false).execute(URL);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    public static void dowloadSelectedFile(Context mContext, String URL) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
//            new DownloadFileAsync(mContext).execute(URL);
//        else
//            new DownloadFileAsync(mContext).execute(URL);
//    }
}
